package com.yanchangapp.ui.activity.mail;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.tencent.smtt.sdk.ValueCallback;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.CheckUtils;
import com.zxl.baselib.util.PerfectClickListener;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.yanchangapp.R;
import com.yanchangapp.adapter.MailUserAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.bean.MailUserBean;
import com.yanchangapp.model.bean.NotifyBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.model.request.SaveDraftRequest;
import com.yanchangapp.model.request.SendMailRequest;
import com.yanchangapp.ui.presenter.MailWriteAtPresenter;
import com.yanchangapp.ui.view.MailWriteAtView;
import com.yanchangapp.widget.X5WebView;
import com.zxl.baselib.widget.NoCoverLoadingDialog;
import com.zxl.baselib.widget.TipDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class MailWriteActivity extends BaseActivity<MailWriteAtView, MailWriteAtPresenter> implements MailWriteAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ivSend)
    ImageView ivSend;
    @BindView(R.id.rvReceivers)
    RecyclerView rvReceivers;
    @BindView(R.id.etReceiver)
    EditText etReceiver;
    @BindView(R.id.ivAddReceiver)
    ImageView ivAddReceiver;
    @BindView(R.id.rvCopies)
    RecyclerView rvCopies;
    @BindView(R.id.etCopy)
    EditText etCopy;
    @BindView(R.id.ivAddCopy)
    ImageView ivAddCopy;
    @BindView(R.id.etTheme)
    EditText etTheme;
    @BindView(R.id.llBody)
    LinearLayout mLlBody;
    @BindView(R.id.webView)
    X5WebView mWebView;
    private static final String DRAFT_ID = "DRAFT_ID";
    private static final String TAG = "写信";
    public static final String USER_BEANS = "user_beans";
    private MailUserAdapter mMailReceiversAdapter;
    private MailUserAdapter mMailCopiersAdapter;
    private List<MailUserBean> mMailReceiverList;
    private List<MailUserBean> mMailCopierList;
    private TipDialog mEnsureThemeDialog,mQuitDialog;
    private String mCurrentTheme;
    private String mWebContent;
    private boolean isFirstIn = true;

    /**
     * 从+号进入写信页面
     * @param context
     */
    public static void show(Activity context) {
        context.startActivity(new Intent(context, MailWriteActivity.class));
        context.overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
    }

    /**
     * 从 选择联系人进入写信页面
     * @param activity
     * @param mailUserBeans
     */
    public static void show(Activity activity,List<MailUserBean> mailUserBeans){
        Intent intent = new Intent(activity,MailWriteActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(USER_BEANS,(Serializable) mailUserBeans);
        intent.putExtras(bundle);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK){
            List<MailUserBean> userBeans = (List<MailUserBean>) data.getExtras().getSerializable(ContactSelectActivity.DATA_BACK);
            // 去除空
            if (userBeans == null){
                userBeans = new ArrayList<>();
            }
            switch (requestCode){
                case ContactSelectActivity.RCODE_RECEIVER:
                    if (userBeans.size() != 0){
                        doFilter(mMailReceiverList,userBeans);
                        setSendIsEnable();
                        mMailReceiversAdapter.notifyDataSetChanged();
                    }
                    break;
                case ContactSelectActivity.RCODE_COPY:
                    if (userBeans.size() != 0){
                        doFilter(mMailCopierList,userBeans);
                        mMailCopiersAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @Override
    protected void init() {
        mMailReceiverList = new ArrayList<>();
        mMailCopierList = new ArrayList<>();
        if (getIntent() != null){
            if (getIntent().hasExtra(USER_BEANS)){
                List<MailUserBean> beans = (List<MailUserBean>) getIntent().getExtras().getSerializable(USER_BEANS);
                if (null != beans){
                    mMailReceiverList.clear();
                    // 进行抄送人的添加
                    mMailReceiverList.addAll(beans);
                }
            }
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_write_mail;
    }

    @Override
    protected MailWriteAtPresenter createPresenter() {
        return new MailWriteAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("写信");
        setSendIsEnable();
        initWebview();
        initAdapter();
    }

    private void initAdapter() {
        LinearLayoutManager receiverManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        LinearLayoutManager copyManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        receiverManager.setSmoothScrollbarEnabled(true);
        receiverManager.setAutoMeasureEnabled(true);
        rvReceivers.setHasFixedSize(true);
        rvReceivers.setNestedScrollingEnabled(false);
        copyManager.setSmoothScrollbarEnabled(true);
        copyManager.setAutoMeasureEnabled(true);
        rvCopies.setHasFixedSize(true);
        rvCopies.setNestedScrollingEnabled(false);
        rvReceivers.setLayoutManager(receiverManager);
        rvCopies.setLayoutManager(copyManager);
        mMailReceiversAdapter = new MailUserAdapter(R.layout.item_user_delete,mMailReceiverList);
        mMailCopiersAdapter = new MailUserAdapter(R.layout.item_user_delete,mMailCopierList);
        rvReceivers.setAdapter(mMailReceiversAdapter);
        rvCopies.setAdapter(mMailCopiersAdapter);
        mMailCopiersAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mMailCopierList.remove(position);
                mMailCopiersAdapter.notifyDataSetChanged();
            }
        });

        mMailReceiversAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mMailReceiverList.remove(position);
                mMailReceiversAdapter.notifyDataSetChanged();
                setSendIsEnable();
            }
        });
    }

    private void initWebview() {
        mWebView.getSettings();
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.addJavascriptInterface(new JSInterface(),"latte");
        mWebView.loadUrl("file:///android_asset/h5/write.html");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstIn){
            isFirstIn = false;
        }else {
            mWebView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.getSettings().setLightTouchEnabled(false);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null){
            mWebView.destroy();
        }
        super.onDestroy();
    }

    // 发送成功

    @Override
    public void sendMailSuccess() {
        UIUtils.showToast("发送成功");
        mRxManager.post(AppConstant.NOTIFY_MAIL_WRITE_SUCCESS,true);
        back();
    }

    // 发送失败
    @Override
    public void sendMailFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void saveDraftSuccess() {
        mRxManager.post(AppConstant.NOTIFY_MAIL_SAVE_DRAFT_SUCCESS,true);
        back();
    }

    @Override
    public void saveDraftFailure(String err) {
        UIUtils.showToast(err);
    }

    //----------------------------------------- webview与js交互事件处理开始------------------------------------

    private final class JSInterface{
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void event(final String info){
            // 获得传递的值
            Log.e(TAG, "event: "+"==== 有数据接受了" );
            Gson gson = new Gson();
            NotifyBean notifyBean = gson.fromJson(info, NotifyBean.class);
            String command =  notifyBean.command;
             if ("write".equals(command)){
                 Log.e(TAG, "接受数据 = "+notifyBean.msg);
                 SendMailRequest sendMailRequest = new SendMailRequest(mMailReceiverList,mMailCopierList,mCurrentTheme,notifyBean.msg);
                 mPresenter.sendMail(sendMailRequest);
            }else if ("back".equals(command)){
                 Log.e(TAG, "接受数据 = "+notifyBean.msg);
                 if (notifyBean.isEmpty){
                     mWebContent = "";
                 }else {
                     mWebContent = notifyBean.msg;
                 }
                 Log.e(TAG, "event: "+mWebContent );
                 if (mailInfoIsNull()){
                     back();
                 }else {
                     showQuitDialog();
                 }
             }
        }
    }

    private void queryWriteData(){
        mWebView.evaluateJavascript("javascript:queryWriteData();",
                new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
    }

    // 查询web数据
    private void queryIsNullData(){
        Log.e(TAG, "queryIsNullData: 中" );
        mWebView.evaluateJavascript("javascript:queryBackData();",
                new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
    }

    //----------------------------------------- webview与js交互事件处理结束 ------------------------------------
    private boolean mailInfoIsNull(){
        boolean rvNUll = mMailReceiverList.size() == 0;
        boolean cpNull = mMailCopierList.size() ==  0;
        boolean themeNull = TextUtils.isEmpty(etTheme.getText().toString());
        boolean contentNull = TextUtils.isEmpty(mWebContent);
        return rvNUll && cpNull && themeNull && contentNull;
    }

    @Override
    protected void initListener() {
        mLlBody.setOnClickListener(v -> {
            if (getCurrentFocus() != null) {
                if (etReceiver.hasFocus()){
                    etReceiver.clearFocus();
                }

                if (etCopy.hasFocus()){
                    etCopy.clearFocus();
                }

                if (etTheme.hasFocus()){
                    etTheme.clearFocus();
                }
                KeyboardHelper.hideKeyboard(mLlBody, getCurrentFocus().getWindowToken());
            }
        });

        // 返回按钮点击事件
        ivToolbarNavigation.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                queryIsNullData();
            }
        });

        ivSend.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                String theme = etTheme.getText().toString();
                if (TextUtils.isEmpty(theme)){
                    showThemeDialog();
                    return;
                }
                mCurrentTheme = theme;
                queryWriteData();
            }
        });

        etReceiver.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus){
                etReceiverIn();
            }
        });

        etCopy.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus){
                etCopyIn();
            }
        });


        // 监听输入框的回车事件...
        etTheme.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER){
                if (event.getAction() == KeyEvent.ACTION_DOWN){
                    etTheme.clearFocus();
                    if (getCurrentFocus() != null) {
                        KeyboardHelper.hideKeyboard(mLlBody, getCurrentFocus().getWindowToken());
                    }
                }
                return  true;
            }
            return false;
        });

        etReceiver.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {
                        MailWriteActivity.this.etReceiverIn();
                    }
                    return true;
                }
                return false;
            }
        });

        etCopy.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER){
                if (event.getAction() == KeyEvent.ACTION_DOWN){
                    etCopyIn();
                }
                return  true;
            }
            return false;
        });

        // 添加按钮的点击事件
        ivAddReceiver.setOnClickListener(v -> ContactSelectActivity.show(MailWriteActivity.this,ContactSelectActivity.RCODE_RECEIVER));

        ivAddCopy.setOnClickListener(v -> ContactSelectActivity.show(MailWriteActivity.this,ContactSelectActivity.RCODE_COPY));
    }

    private void back(){
        finish();
        overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
    }

    private void showThemeDialog() {
        if (mEnsureThemeDialog == null){
            mEnsureThemeDialog = new TipDialog.Builder(this)
                    .setMessage("确定发送无主题邮件?")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            mEnsureThemeDialog.dismiss();
                            // 执行确认主题逻辑
                            mCurrentTheme = "来自"+ UserCache.getName() +"的邮件";
                            queryWriteData();
                        }
                    }).build();
        }
        mEnsureThemeDialog.show();
    }

    private void showQuitDialog() {
        if (mQuitDialog == null){
            mQuitDialog = new TipDialog.Builder(this)
                    .setMessage("是否保存为草稿？")
                    .setEnsureText("保存")
                    .setCancelText("不保存")
                    .setCancelCickListener(new TipDialog.CancelClickListener() {
                        @Override
                        public void onCancelClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            back();
                        }
                    })
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            httpSaveDraft();
                        }
                    }).build();
        }
        mQuitDialog.show();
    }

    // 记性保存草稿
    private void httpSaveDraft() {
        SaveDraftRequest saveDraftRequest = new SaveDraftRequest(0,mMailReceiverList,mMailCopierList,etTheme.getText().toString(),mWebContent);
        mPresenter.saveDraftMail(saveDraftRequest);
    }


    private void etReceiverIn(){
        String receiver = etReceiver.getText().toString();
        if (CheckUtils.isEmail(receiver)){
            String[] rvArray = receiver.split("@");
            MailUserBean mailUserBean = new MailUserBean(receiver, rvArray[0], rvArray[0]);
            doFilter(mMailReceiverList,mailUserBean);
            mMailReceiversAdapter.notifyDataSetChanged();
        }
        setSendIsEnable();
        etReceiver.setText("");
    }

    /**
     * 设置发送按钮是否可见...
     */
    private void setSendIsEnable(){
        if (mMailReceiverList.size() > 0){
            ivSend.setEnabled(true);
        }else {
            ivSend.setEnabled(false);
        }
    }

    private void etCopyIn(){
        String copy = etCopy.getText().toString();
        if (CheckUtils.isEmail(copy)){
            String[] rvArray = copy.split("@");
            MailUserBean mailUserBean = new MailUserBean(copy, rvArray[0], rvArray[0]);
            doFilter(mMailCopierList,mailUserBean);
            mMailCopiersAdapter.notifyDataSetChanged();
        }
        etCopy.setText("");
    }


    /**
     * 进行合并筛选
     * @param target
     * @param two
     */
    private void doFilter(List<MailUserBean> target,List<MailUserBean> two){
        if (target.size() == 0){
            target.addAll(two);
            return;
        }
        List<MailUserBean> three = new ArrayList<>();
        for (int i=0;i<two.size();i++){
            MailUserBean targetBean =  two.get(i);
            for (int j=0;j<target.size();j++){
                MailUserBean nextBean = target.get(j);
                if (targetBean.getAddress().equals(nextBean.getAddress())){
                    target.set(j,targetBean);
                    break;
                }
                if (j == (target.size()-1)){
                    three.add(targetBean);
                }
            }
        }
        target.addAll(three);
    }

    private void doFilter(List<MailUserBean> target,MailUserBean bean){
        if (target.size() == 0){
            target.add(bean);
        }
        for (int i=0;i<target.size();i++){
            MailUserBean userBean = target.get(i);
            if (bean.getAddress().equals(userBean.getAddress())){
                target.set(i,bean);
                break;
            }
            if (i == (target.size()-1)){
                target.add(bean);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            queryIsNullData();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
